package App.Filter;

//import App.Config.JwtConfig;

import App.Model.Account.CrmToken;
import App.Model.Account.CrmUser;
import App.Model.Account.JWTResponse;
import App.Repository.AccountRepository;
import App.Utility.JwtAuth;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import org.bouncycastle.cms.PasswordRecipientId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.stereotype.Component;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;


public class JwtAuthenticationFilter extends BasicAuthenticationFilter {

    //@Autowired
    private final JwtAuth _jwtAuth;

    //@Autowired
    private AccountRepository _accountRepository;

    public JwtAuthenticationFilter(AuthenticationManager authManager, JwtAuth jwtAuth, AccountRepository accountRepository) {
        super(authManager);
        this._jwtAuth = jwtAuth;
        this._accountRepository = accountRepository;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest req,
                                    HttpServletResponse res,
                                    FilterChain chain) throws IOException, ServletException {
        try {
            // 1. get the authentication header. Tokens are supposed to be passed in the authentication header
            String header = req.getHeader("Authorization");

            // 2. validate the header and check the prefix
            if (header == null || !header.startsWith("Bearer ")) {
                // If not valid, go to the next filter.
                SecurityContextHolder.clearContext();
                chain.doFilter(req, res);
                return;
            } else {
                String _token = getToken(header);
                boolean _isTokenValid = _accountRepository.IsTokenValid(_token);
                if (!_isTokenValid) {
                    SecurityContextHolder.clearContext();
                    chain.doFilter(req, res);
                    return;
                }
            }

            UsernamePasswordAuthenticationToken authentication = getAuthentication(req, res);
            SecurityContextHolder.getContext().setAuthentication(authentication);
        } catch (Exception ex) {
            // In case of failure. Make sure it's clear; so guarantee user won't be authenticated
            SecurityContextHolder.clearContext();
            ex.printStackTrace();
        }

        //set token for response


        chain.doFilter(req, res);
    }

    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request, HttpServletResponse res) {

        try {
            String token = request.getHeader("Authorization");
            if (token != null) {
                // parse the token.
                CrmUser _userInfo = _jwtAuth.getTokenUserInfo(token);
                String _userJson = JSON.toJSONString(_userInfo);
                String _token = getToken(token);

                String _url = request.getContextPath();
                _url = request.getRequestURI();

                // _url=request.getQueryString();
                // StringBuilder requestURL = new StringBuilder(request.getRequestURL().toString());
                //  String qukeryString = request.getQueryString();

                if (!_url.equals("/api/account/logout")&&!_url.equals("/api/account/isconfirmed")) {
                    boolean _needUpdate = _accountRepository.NeedCreateNewToken(_token);
                    if (_needUpdate) {

                      CrmToken _theToken= _accountRepository.GetTokens(_token);
                        if(_theToken!=null){
                            res.addHeader("token_new", _theToken.getToken());
                        }else{
                            JWTResponse _jwtResponse = _jwtAuth.buildTokenNew(_userInfo.getId(), _userInfo.getUsername());
                            String _newToken = _jwtResponse.getToken();
                            Date _newExpiretionDate = _jwtResponse.getExpiretionDate();
                            _accountRepository.InsertTokenHistory(_userInfo.getId(), _newToken, _newExpiretionDate,_token);
                            res.addHeader("token_new", _newToken);
                        }
                    } else {
                        _accountRepository.UpdateTokenLatestCallApiTime(_token);
                    }
                }

                return new UsernamePasswordAuthenticationToken(_userJson, null, new ArrayList<>());
            }
            return null;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    private String getToken(String token) {
        return token.replace("Bearer ", "");

    }

    //end of class
}

